#!/bin/bash

# 检查参数数量
if [ "$#" -ne 3 ]; then
  echo "Usage: $0 <executable_file> <number_of_loops> <wait_seconds>"
  exit 1
fi

# 赋值输入的参数
executable_file=$1
number_of_loops=$2
wait_seconds=$3

# 检查文件是否可执行
if [ ! -x "$executable_file" ]; then
  echo "Error: File '$executable_file' is not executable or does not exist."
  exit 2
fi

# 检查等待时间是否为正整数
if ! [[ "$wait_seconds" =~ ^[0-9]+$ ]]; then
  echo "Error: Wait time must be a positive integer."
  exit 3
fi

# 循环执行文件
for (( i=0; i<number_of_loops; i++ )); do
  echo "Loop $((i+1)) of $number_of_loops"
  (
    # 运行文件并向其传递输入
    echo "Starting the executable with highest priority."
    echo "Inputting 'who are you?' and '!exit' with $wait_seconds-second intervals."

    # 使用子shell和管道，确保可以将命令写入被执行文件的标准输入
    (
      sleep "$wait_seconds"
      echo "who are you?"
      sleep "$wait_seconds"
      echo "!exit"
    ) | nice -n -20 "$executable_file"
  )
done

echo "All loops completed."
